package com.yanqu.road.server.manager.cross.battle;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.dafuweng.DfwAttackBossResult;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.rank.yrank.UnionYRank;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUnion;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.pb.monopoly.MonopolyProto;
import com.yanqu.road.server.TempCrossMgr;
import com.yanqu.road.server.manager.activity.ActivityInfoMgr;
import com.yanqu.road.server.manager.union.activitygroup.Cross2UnionActivityGroupMgr;
import com.yanqu.road.server.manager.yrank.CrossYRankMgr;
import com.yanqu.road.utils.date.DateHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

public class DaFuWengMgr extends TempCrossMgr {

    private static Map<Integer, Map<Integer, DaFuWengActivity>> activityGroupMap = new ConcurrentHashMap<>();

    // 清理旧数据间隔
    public static long CLEAN_INTERVAL = 1L * 60L * 60L * 1000L;

    public static DfwAttackBossResult tenRollShareAndAttackBoss(int activityId, long serverId, long userId, int damage, MonopolyProto.MonopolyPlayerMsg monopolyPlayer) {
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, userId);
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID) {
            return null;
        }

        DaFuWengActivity daFuWengActivity = DaFuWengMgr.getDaFuWengActivity(activityId, groupId);
        if (daFuWengActivity == null) {
            return null;
        }

        return daFuWengActivity.tenRollShareAndAttackBoss(serverId, userId, damage, monopolyPlayer);
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean save() {
        for (Map<Integer, DaFuWengActivity> map : activityGroupMap.values()) {
            for (DaFuWengActivity activity : map.values()) {
                activity.save();
            }
        }
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    /**
     * 获取活动
     */
    public static synchronized DaFuWengActivity getDaFuWengActivity(int activityId, int groupId) {
        // 【活动ID判断】
        if (activityGroupMap.get(activityId) == null) {
            activityGroupMap.put(activityId, new ConcurrentHashMap<>());
        }
        Map<Integer, DaFuWengActivity> groupMap = activityGroupMap.get(activityId);

        // 【分组ID判断】
        UnionActivityGroup groupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, groupId);
        if (groupData == null) {
            return null;
        }
        if (groupMap.get(groupId) == null) {
            ActivityInfo activityInfo = ActivityInfoMgr.getActivityInfo(activityId);
            if (activityInfo == null) {
                return null;
            }
            DaFuWengActivity activity = new DaFuWengActivity(activityInfo, groupId);
            groupMap.put(groupId, activity);
        }
        DaFuWengActivity activity = groupMap.get(groupId);
        return activity;
    }

    /**
     * 从排行榜获取2个随机商会
     *
     * @return 获取失败：空数组
     */
    public static List<MonopolyProto.MonopolyUnionMsg> getRandomZaoYaoUnionMsg(int activityId, String unionUid) {
        int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityId, unionUid);
        if (groupId == UnionActivityGroupHelper.NO_GROUP_ID) {
            return new ArrayList<>();
        }

        List<UnionYRank> baseRankList = CrossYRankMgr.getSortUnionRankList(activityId, groupId, String.valueOf(eGamePlayerEventType.DaFuWengUnionScoreRank.getValue()));
        if (baseRankList.size() < 3) {
            return appendUnionMsg(activityId, unionUid, groupId, baseRankList);
        }
        ArrayList<UnionYRank> rankList = new ArrayList<>(baseRankList);

        // 随机抽商会
        List<MonopolyProto.MonopolyUnionMsg> resultList = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < 2 && rankList.size() > 0; i++) {
            int index = random.nextInt(rankList.size());
            UnionYRank rank = rankList.get(index);
            rankList.remove(index);
            if (rank.getUnionUid().equals(unionUid)) {
                i--;
                continue;
            }

            int rankNum = CrossYRankMgr.getUnionRankNum(baseRankList, rank.getUnionUid());

            MonopolyProto.MonopolyUnionMsg.Builder builder = getUnionMsgBuilder(rankNum, rank.getUnionUid(), rank.getValue().intValue(), rank.getUnionBaseInfo());
            resultList.add(builder.build());
        }
        // 返回
        return resultList;
    }

    private static List<MonopolyProto.MonopolyUnionMsg> appendUnionMsg(int activityId, String unionUid, int groupId, List<UnionYRank> baseRankList) {
        List<MonopolyProto.MonopolyUnionMsg> msgList = new ArrayList<>();
        List<String> unionUidList = new ArrayList<>();
        int rankNum = 0;
        //榜单多少给多少
        for (UnionYRank unionYRank : baseRankList) {
            rankNum ++;
            if (unionYRank.getUnionUid().equals(unionUid)) {
                continue;
            }
            unionUidList.add(unionYRank.getUnionUid());
            MonopolyProto.MonopolyUnionMsg.Builder builder = getUnionMsgBuilder(rankNum, unionYRank.getUnionUid(), unionYRank.getValue().intValue(), unionYRank.getUnionBaseInfo());
            msgList.add(builder.build());
        }

        //随机补充1、2个，榜单不够时候，从参加名单的来，因为要知道商会的金币数
        UnionActivityGroup activityGroup = Cross2UnionActivityGroupMgr.getGroupData(activityId, groupId);
        Random random = new Random();
        if(activityGroup != null){
            ArrayList<UnionActivityGroupUnion> list = new ArrayList<>(activityGroup.getUnionDataMap().values());
            while (list.size() > 0 && msgList.size() < 3){
                int index = random.nextInt(list.size());
                UnionActivityGroupUnion groupUnion = list.remove(index);
                if(groupUnion.getUnionUid().equals(unionUid)){
                    continue;
                }
                if(unionUidList.contains(groupUnion.getUnionUid())){
                    continue;
                }
                unionUidList.add(groupUnion.getUnionUid());
                MonopolyProto.MonopolyUnionMsg.Builder builder = getUnionMsgBuilder(++rankNum, groupUnion.getUnionUid(), 0, groupUnion.getUnionBaseInfo());
                msgList.add(builder.build());
            }
        }
        if(msgList.size() <= 2){
            return msgList;
        }
        // 随机2个
        // 随机抽商会
        List<MonopolyProto.MonopolyUnionMsg> resultList = new ArrayList<>();
        for (int i = 0; i < 2 && msgList.size() > 0; i++) {
            int index = random.nextInt(msgList.size());
            resultList.add(msgList.remove(index));
        }
        return resultList;
    }

    private static MonopolyProto.MonopolyUnionMsg.Builder getUnionMsgBuilder(int rankNum, String unionUid, int score, UnionBaseInfo unionBaseInfo) {
        MonopolyProto.MonopolyUnionMsg.Builder builder = MonopolyProto.MonopolyUnionMsg.newBuilder();
        builder.setRank(rankNum);
        builder.setUnionUid(unionUid);
        builder.setSilverScore(score);
        builder.setUnionData(UnionBasePb.parseUnionBaseTempMsg(unionBaseInfo));
        return builder;
    }

    /**
     * 清空3天前的活动数据
     */
    public static void cleanMemory() {
        long now = System.currentTimeMillis();
        for (Map.Entry<Integer, Map<Integer, DaFuWengActivity>> entry : activityGroupMap.entrySet()) {
            int activityId = entry.getKey();
            Map<Integer, DaFuWengActivity> groupMap = entry.getValue();
            for (Map.Entry<Integer, DaFuWengActivity> entry2 : groupMap.entrySet()) {
                int groupId = entry2.getKey();
                DaFuWengActivity activity = entry2.getValue();
                if (now - activity.getCrossConfig().getActivityInfo().getEndShowTime() > DateHelper.HOUR_MILLIONS * 12) {
                    groupMap.remove(groupId);
                    getLogger().info("Cross2 DaFuWengMgr cleanMemory : remove activity from dfwDataMap, activityId={}, groupId={}", activityId, groupId);
                }
            }
            if (groupMap.isEmpty()) {
                activityGroupMap.remove(activityId);
                getLogger().info("Cross2 DaFuWengMgr cleanMemory : remove activity from dfwDataMap, activityId={}, all remove.", activityId);
            }
        }
    }

    /**
     * 清空旧数据（boss榜单、boss攻击记录）
     */
    public static void cleanOldData() {
        for (Map<Integer, DaFuWengActivity> map : activityGroupMap.values()) {
            for (DaFuWengActivity activity : map.values()) {
                activity.cleanActivityOldData();
            }
        }
    }

    public boolean removeExpireData() {
        // cleanMemory里面有了
        return true;
    }

}
